package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.lanjiu.lib.imclient.dto.GroupDto;
import com.lanjiu.lib.imclient.dto.extra.SearchResultDto;
import com.lanjiu.lib.imclient.dto.user.RegisteredUserDto;
import com.lanjiu.lib.imclient.dto.user.TouristsUserDto;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.utils.CollectionUtils;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.SearchListAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.SearchBean;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.SearchListView;
import com.ljkj.cordial.chat.util.ObserverThread;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @description:
 * @author: Panwei
 * @date: 2020/2/13 14:06
 */
public class SearchListActivity extends AppEventActivity<SearchListView> {

    public static final int SEARCH_TYPE_FRIEND = SearchListAdapter.ITEM_FRIEND;
    public static final int SEARCH_TYPE_GROUP = SearchListAdapter.ITEM_GROUP;

    @BindView(R.id.recycler_ui)
    RecyclerView mRecyclerView;
    @BindView(R.id.no_result)
    TextView mNoResultView;

    private SearchListAdapter mAdapter;
    private String mSearchKeyword;
    private int mSearchType;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_search_list;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        Intent intent = getIntent();
        mSearchKeyword = intent.getStringExtra("Extra_Search_Keyword");
        mSearchType = intent.getIntExtra("Extra_Search_Type", SearchListAdapter.ITEM_FRIEND);
        getToolbar().setTitle(mSearchType == SEARCH_TYPE_FRIEND ? "查找好友" : "查找群组");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);
        mAdapter = new SearchListAdapter(this);
        mAdapter.setOnItemClickListener((view, item, position) -> {
            if (view.getId() == R.id.tv_btn) {
                if (item.itemType == SearchListAdapter.ITEM_FRIEND) {
                    SearchBean searchBean = item.toFriend(mSearchKeyword);
                    AddFriendActivity.jumpTo(this, Canstants.KEY_SEARCH_FRIEND, searchBean);
                } else {
                    SearchBean searchBean = item.toGroup(mSearchKeyword);
                    AddFriendActivity.jumpTo(this, Canstants.KEY_SEARCH_GROUP, searchBean);
                }
            } else {
                if (item.itemType == SearchListAdapter.ITEM_FRIEND) {
                    if (item.relation == SearchListAdapter.RELATION_FRIENDLY) {
                        String userType = IMSUtils.userTypeAnalysis(item.id);
                        FriendInfoActivity.jumpTo(this, IMSContacts.UserType.REGISTERED_USER.equals(userType) ? Canstants.KEY_REGISTER : Canstants.KEY_VISITOR, item.name, item.id, userType);
                    } else if (item.relation == SearchListAdapter.RELATION_SELF) {
                        startActivity(new Intent(this, PersonalActivity.class));
                    } else {
                        SearchBean searchBean = item.toFriend(mSearchKeyword);
                        SearchResultActivity.jumpTo((Activity) mContext, Canstants.KEY_SEARCH_FRIEND, searchBean);
                    }
                } else {
                    if (item.relation == SearchListAdapter.RELATION_FRIENDLY) {
                        GroupChatSetActivity.jumpToSend(this, item.name, item.id, IMSUtils.userTypeAnalysis(item.id));
                    } else {
                        SearchBean searchBean = item.toGroup(mSearchKeyword);
                        SearchResultActivity.jumpTo((Activity) mContext, Canstants.KEY_SEARCH_GROUP, searchBean);
                    }
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected int setupEventBusRegSite() {
        return EVENT_REG_ON_CREATE;
    }

    @Override
    protected void afterOnCreateRegisterEventBus() {
        super.afterOnCreateRegisterEventBus();
        if (mSearchType == SEARCH_TYPE_GROUP)
            obtainView().doGroupFind(mSearchKeyword);
        else
            obtainView().doFriendFind(mSearchKeyword);
    }

    @Override
    protected SearchListView bindNettyMessageView() {
        return new SearchListView(new SearchListView.SearchListCallback() {
            @Override
            public void onFriendFindCallback(int code, String msg, SearchResultDto data) {
                setupFriendDataSet(data);
            }

            @Override
            public void onGroupFindCallback(int code, String msg, List<GroupDto> data) {
                setupGroupDataSet(data);
            }
        });
    }

    private void setupFriendDataSet(SearchResultDto data) {
        ObserverThread.create().onNextThread2(new ObserverThread.OnListActionListener<SearchListAdapter.ItemBean>() {
            @Override
            public void onAction(List<SearchListAdapter.ItemBean> list) {
                if (!CollectionUtils.isEmpty(list))
                    mAdapter.setDataSet(list);
                else
                    mNoResultView.setVisibility(View.VISIBLE);
            }

            @Override
            public List<SearchListAdapter.ItemBean> onThreadAction() {
                List<SearchListAdapter.ItemBean> itemList = new ArrayList<>();
                if (data != null) {
                    if (!CollectionUtils.isEmpty(data.getRegisteredUserDtoList())) {
                        for (RegisteredUserDto registeredUserDto : data.getRegisteredUserDtoList())
                            itemList.add(new SearchListAdapter.ItemBean(registeredUserDto));
                    }
                    if (!CollectionUtils.isEmpty(data.getTouristsUserDtoList())) {
                        for (TouristsUserDto touristsUserDto : data.getTouristsUserDtoList())
                            itemList.add(new SearchListAdapter.ItemBean(touristsUserDto));
                    }
                }
                List<FriendTable> search = FriendTable.search(mSearchKeyword);
                for (FriendTable table : search) {
                    if (!contains(itemList, table.getFriendUserId()))
                        itemList.add(new SearchListAdapter.ItemBean(table));
                }
                return itemList;
            }
        });
    }

    private void setupGroupDataSet(List<GroupDto> data) {
        ObserverThread.create().onNextThread2(new ObserverThread.OnListActionListener<SearchListAdapter.ItemBean>() {
            @Override
            public void onAction(List<SearchListAdapter.ItemBean> list) {
                if (!CollectionUtils.isEmpty(list))
                    mAdapter.setDataSet(list);
                else
                    mNoResultView.setVisibility(View.VISIBLE);
            }

            @Override
            public List<SearchListAdapter.ItemBean> onThreadAction() {
                List<SearchListAdapter.ItemBean> itemList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(data)) {
                    for (GroupDto datum : data)
                        itemList.add(new SearchListAdapter.ItemBean(datum));
                }
                List<GroupTable> search = GroupTable.search(mSearchKeyword);
                for (GroupTable table : search) {
                    if (!contains(itemList, table.getGroupId()))
                        itemList.add(new SearchListAdapter.ItemBean(table));
                }
                return itemList;
            }
        });
    }

    public boolean contains(List<SearchListAdapter.ItemBean> itemList, String id) {
        for (SearchListAdapter.ItemBean itemBean : itemList) {
            if (itemBean.id.equals(id)) {
                return true;
            }
        }
        return false;
    }

    public static void jumpTo(Activity context, int searchType, String keyword) {
        Intent intent = new Intent(context, SearchListActivity.class);
        intent.putExtra("Extra_Search_Type", searchType);
        intent.putExtra("Extra_Search_Keyword", keyword);
        context.startActivityForResult(intent, Canstants.REQUEST_CODE_BACK);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Canstants.REQUEST_CODE_BACK && resultCode == Canstants.REQUEST_CODE_BACK) {
            setResult(Canstants.REQUEST_CODE_BACK);
            finish();
        }
    }
}
